package com.itheima.case2.web;

import com.itheima.case2.pojo.User;
import com.itheima.case2.service.UserService;
import com.itheima.case2.service.impl.UserServiceImpl;
import com.itheima.case2.utils.BaseController;
import com.itheima.case2.utils.BeansFactory;
import com.itheima.case2.vo.PageBean;
import com.itheima.case2.vo.Result;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class User2Servlet extends BaseServlet {
    public void deleteUserById(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("根据id删除用户");
    }

    public void addUser(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("添加用户");

    }

    public void updateUser(HttpServletRequest request, HttpServletResponse response)  {
        try {
            User user = BaseController.parseJSON2Object(request, User.class);
            UserService userService = BeansFactory.getSingleBean("userService");
            userService.updataUser(user);
            response.sendRedirect("/user?methodName=findAllUsersByPage&curPage=1&pageSize=5");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void findAllUsers(HttpServletRequest request, HttpServletResponse response) {

        System.out.println("查询所有用户");
    }

    public void findAllUsersByPage(HttpServletRequest request, HttpServletResponse response) {
        int curPage = Integer.parseInt(request.getParameter("curPage"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        UserServiceImpl userservice = new UserServiceImpl();
        PageBean pb = userservice.findAllUserByPage(curPage, pageSize);
        response.setContentType("text/html;charset=utf-8");
        try {
            BaseController.printResult(response, new Result(true, "分页查询成功", pb));
        } catch (IOException e) {
            e.printStackTrace();

            try {
                BaseController.printResult(response, new Result(false, "分页查询失败", null));
            } catch (IOException e1) {
                e.printStackTrace();
            }

        }
    }
}
